//
//  PageController.m
//  PaypalDemo
//
//  Created by nsm on 2020/10/17.
//  Copyright © 2020 nani. All rights reserved.
//

#import "PageController.h"
#import "PageCell.h"

static NSString * const kCellReuseIdentifier = @"kCellReuseIdentifier";

@interface PageController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tv;
@property (nonatomic, strong) PageCell *currentCell;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic) BOOL isDataLoading;
@end

@implementation PageController

#pragma mark - lifeCycle
- (instancetype)init {
    self = [super init];
    if (self) {
        _dataArray = @[].mutableCopy;
        for (int i=0; i<10; i++) {
            [_dataArray addObject:@{}];
        }
    }
    return self;
}

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
        
    _tv = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavBarHeight)
                                       style:UITableViewStylePlain];
    _tv.decelerationRate = UIScrollViewDecelerationRateFast;
    _tv.pagingEnabled = YES;
    _tv.delegate = self;
    _tv.dataSource = self;
    _tv.estimatedRowHeight = 0;
    _tv.estimatedSectionHeaderHeight = 0;
    _tv.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11, *)) {
        _tv.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _tv.showsVerticalScrollIndicator = NO;
    _tv.showsHorizontalScrollIndicator = NO;
    [_tv registerClass:PageCell.class forCellReuseIdentifier:kCellReuseIdentifier];
    [self.view addSubview:_tv];
    
    [_tv reloadData];
    
    [_tv setContentOffset:CGPointMake(0, (kScreenHeight-kNavBarHeight) * _index) animated:NO];
    [self startPlay];
}

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScreenHeight - kNavBarHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PageCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseIdentifier];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0f
                                           green:arc4random()%255/255.0f
                                            blue:arc4random()%255/255.0f
                                           alpha:1];
    cell.textLabel.text = [NSString stringWithFormat:@"下标:%@", @(indexPath.row)];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 预加载
    NSLog(@"%s[%zd,%zd]", __func__, indexPath.section, indexPath.row);
    NSLog(@"%@", tableView.indexPathsForVisibleRows) ;
    NSInteger lastRow = tableView.indexPathsForVisibleRows.lastObject.row;
    NSInteger total = _dataArray.count;
    if (lastRow >= total-3) [self loadMore];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"%s[%zd,%zd]", __func__, indexPath.section, indexPath.row);
//    NSLog(@"%@", tableView.indexPathsForVisibleRows) ;
}

#pragma mark - 业务处理
- (void)startPlay {
    // 因为开启了pagingEnabled,所以此时肯定是整屏的
    _currentCell = self.tv.visibleCells.firstObject;
    _currentCell.textLabel.text = @"我去";
}

- (void)loadMore {
    // 如果没有更多数据了,不能加载
    // 如果正在加载中,不能重复加载
    if (_isDataLoading) return;
    
    NSLog(@"%s", __func__);

    _isDataLoading = YES;
    
    // 模拟预加载数据
    NSMutableArray *indexPaths = @[].mutableCopy;
    NSMutableArray *datas = @[].mutableCopy;
    NSInteger count = _dataArray.count;
    for (int i=0; i<10; i++) {
        [indexPaths addObject:[NSIndexPath indexPathForRow:count+i inSection:0]];
        [datas addObject:@{}];
    }
    
    [_dataArray addObjectsFromArray:datas];
    [_tv reloadData];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.isDataLoading = NO;
    });
}

#pragma mark - 滚动试图
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    int lastRow = scrollView.contentOffset.y / _tv.height;
//    NSInteger total = _dataArray.count;
//    if (total>3 && lastRow>=total-3) {
//        [self loadMore];
//    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"%s", __func__);
    // NSLog(@"%s[%zd,%zd]", __func__, indexPath.section, indexPath.row);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"%s", __func__);
    [self startPlay];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"%s[%@]", __func__, decelerate?@"YES":@"NO");
    if (decelerate) return;
	[self startPlay];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    NSLog(@"%s", __func__);
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private

#pragma mark - action

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
